package com.training.client;

import java.io.*;
import java.net.Socket;

/**
 * Created by Ywen on 2018/12/27.
 */
public class Handler implements Runnable {
    private Socket socket;
    InputStream inputStream;
    PrintStream out;

    public Handler(Socket socket) {
        this.socket = socket;
        try {
            inputStream = socket.getInputStream();
            out = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String handle(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            String content = bufferedReader.readLine();
            if (content != null) {
                String[] split = content.split(" ");
                if (split.length != 3) {
                    error(400, "请求错误");
                    return null;
                }
                return split[1];
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    private void error(int errorCode, String errorMsg) {
        out.println("HTTP/1.0 " + errorCode + " " + errorMsg);
        out.println("content-type: text/html");
        out.println();
        out.flush();
        out.close();
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void response(String res) {
        File file = new File("d:" + File.separator + "wwwroot" + res);
        if (!file.exists()) {
            error(404, "文件没有找到");
            return;
        }
        try {
            InputStream inputStream = new FileInputStream(file);
            int len = (int) file.length();
            byte[] content = new byte[len];
            inputStream.read(content);
            out.println("HTTP/1.0 200 OK");
            out.println("content-length:"+len);
            out.println();
            out.write(content);
            out.flush();
            out.close();
            inputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        String res = handle(inputStream);
        response(res);
    }
}
